package com.kittyhawks.bksystem.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.kittyhawks.bksystem.entity.*;
import com.kittyhawks.bksystem.service.PgrInfoService;
import com.kittyhawks.bksystem.service.PgrRotaService;
import com.kittyhawks.bksystem.util.JSONResult;
import com.kittyhawks.bksystem.util.JSONUtil;
import com.kittyhawks.bksystem.util.WebUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author zhanghan
 * 摄影师后台管理Controller
 */
@Controller
@RequestMapping("/pgrInfo")
public class PgrInfoController {

    @Autowired
    PgrInfoService pgrInfoService;
    @Autowired
    PgrRotaService pgrRotaService;
    @Autowired
    JSONUtil jsonUtil;

    final String SUCCESSED = "0";
    final String FAILED = "1";

    WebUtil webUtil = new WebUtil();

    /**
     * 摄影师后台管理首页
     *
     * @return pgrInfoSearch.html
     */
    @RequestMapping("/index")
    public String pgrInfo() {

        return "pgrInfoSearch";
    }

    /**
     * 得到选择的摄影师详细资料和预定时间表
     */
    @RequestMapping(value = "/getDetails")
    @ResponseBody
    public String returnDeatils(@RequestBody String json) throws IOException {

        String newId = "";

        Map<String, String> map = jsonUtil.readValue(json, Map.class);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("id")) {
                newId = entry.getValue();
            }
        }

        Photographer photographer = pgrInfoService.getInfoById(newId);

        String jsonList = jsonUtil.toJSon(photographer);

        return jsonList;
    }

    /**
     * 根据admin表remark对应权限（1超级管理员，2yige，3fuyou，4qinyu，5xiaoying）查询所属公司下的摄影师信息
     */
    @RequestMapping("/getAllInfo")
    @ResponseBody
    public String getAllInfo(HttpSession session) throws JsonProcessingException {

        Admin admin = (Admin) webUtil.getCurrentUser(session);
        String id = admin.getId();
        List<Photographer> lists = pgrInfoService.getAllInfo(id);
        String jsonList = jsonUtil.toJSon(lists);
        return jsonList;
    }

    /**
     * 修改摄影师信息
     */
    @RequestMapping(value = "/alterInfo", method = RequestMethod.POST)
    @ResponseBody
    public String alterInfo(@RequestBody String json) throws IOException {

        String id = "";
        String name = "";
        int age = 0;
        String mobile = "";
        String company = "";
        String gender = "";
        String username = "";
        String password = "";
        String status = "";

        Map<String, String> map = jsonUtil.readValue(json, Map.class);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("id")) {
                id = entry.getValue();
            }
            if (entry.getKey().equals("name")) {
                name = entry.getValue();
            }
            if (entry.getKey().equals("age")) {
                age = Integer.valueOf(entry.getValue());
            }
            if (entry.getKey().equals("mobile")) {
                mobile = entry.getValue();
            }
            if (entry.getKey().equals("company")) {
                company = entry.getValue();
            }
            if (entry.getKey().equals("username")) {
                username = entry.getValue();
            }
            if (entry.getKey().equals("password")) {
                password = entry.getValue();
            }
            if (entry.getKey().equals("status")) {
                status = entry.getValue();
            }
            if (entry.getKey().equals("gender")) {
                gender = entry.getValue();
                if (gender.equals("1")) {
                    gender = "男";
                }
                if (gender.equals("2")) {
                    gender = "女";
                }
            }
        }
        System.out.println("status : " + status);
        Photographer photographer = new Photographer(id, name, mobile, username, password, company, age, gender, status);
        String ruselt = pgrInfoService.alterInfo(photographer);
        Map<String, String> map1 = new HashMap<>();
        map1.put("result", ruselt);
        String json1 = jsonUtil.toJSon(map1);

        return json1;
    }

    /**
     * pgrInfoSearch.html页面的搜索按钮对应方法
     */
    @RequestMapping(value = "/searchPgrInfo", method = RequestMethod.POST)
    @ResponseBody
    public String searchPgrInfo(@RequestBody String json) throws IOException {

        String name = "";
        String company = "";
        Map<String, String> map = jsonUtil.readValue(json, Map.class);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey() == "name") {
                name = entry.getValue();
            }
            if (entry.getKey() == "company") {
                company = entry.getValue();
            }
        }
        List<Photographer> lists = new ArrayList<>();
//        System.out.println("name : " + name + " company : " + company);
        if (name == "" && company == "") {
            lists = pgrInfoService.selectInfo();
        }
        if (name != "" && company == "") {
            lists = pgrInfoService.selectInfoByName(name);
        }
        if (name == "" && company != "") {
            lists = pgrInfoService.selectInfoByCompany(company);
        }
        if (name != "" && company != "") {
            lists = pgrInfoService.selectInfoByNameAndCompany(name, company);
        }

        String jsonList = jsonUtil.toJSon(lists);
        return jsonList;
    }

    /**
     * 在pgrInfoManage.html显示从明天开始的七天日期
     *
     * @return "YY-MM-DD"
     */
    @RequestMapping("/getDate")
    @ResponseBody
    public String[] getDate() {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        String[] dateArray = new String[7];

        for (int i = 0; i < 7; i++) {
            calendar.setTime(date);
            calendar.add(calendar.DATE, +1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
            date = calendar.getTime();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(date);
            dateArray[i] = dateString;
        }
        return dateArray;
    }

    /**
     * 将1~28数字（eg：1对应今天后第一天第一场，5对应今天后第二天第一场）转换成对应第几天第几场次插入数据库
     * 增加摄影师可预约时间
     *
     * @return 成功0，失败1
     */
    @RequestMapping("/book")
    @ResponseBody
    public String addBook(@RequestBody String json) throws IOException {

        int index;
        int day = 0;//今天后的第几天
        int bookTime = 0;//对应的第几场次
        int sign = -1;//操作，1：插入，0：删除
        String pgrId = "";//摄影师id
        Rota rota;

        Map<String, String> map = jsonUtil.readValue(json, Map.class);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey() == "index") {

                index = Integer.valueOf(entry.getValue());
                if (index == 4 || index == 8 || index == 12 || index == 16 || index == 20 || index == 24 || index == 28) {
                    day = index / 4;
                    bookTime = 4;
                } else {
                    day = index / 4 + 1;
                    bookTime = index % 4;
                }

            }
            if (entry.getKey() == "sign") {
                sign = Integer.valueOf(entry.getValue());
            }
            if (entry.getKey() == "id") {
                pgrId = entry.getValue();
            }

        }

        Date bookDay = new Date();//取时间
        Calendar calendar = new GregorianCalendar();

        calendar.setTime(bookDay);
        calendar.add(calendar.DATE, day);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
        bookDay = calendar.getTime();

        rota = new Rota(pgrId, bookDay, bookTime);
        if (sign == 1) {
            String result = pgrRotaService.addBook(rota);
            Map<String, String> map1 = new HashMap<>();
            map1.put("result", result);
            String json1 = jsonUtil.toJSon(map1);
            return json1;
        }
        if (sign == 0) {
            String result = pgrRotaService.removeBook(rota);
            Map<String, String> map1 = new HashMap<>();
            map1.put("result", result);
            String json1 = jsonUtil.toJSon(map1);
            return json1;
        }
        return null;
    }

    /**
     * pgrInfoSearch.html页面“查看”按钮对应方法
     *
     * @return 显示在页面上的数据
     */
    @RequestMapping("/getRota")
    @ResponseBody
    public String getPgrRotaById(@RequestBody String json) throws Exception {

        String pgrId = "";
        Map<String, String> map = jsonUtil.readValue(json, Map.class);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("id")) {
                pgrId = entry.getValue();
            }
        }

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(date);

        List<Rota> dbRotaList = pgrRotaService.getRota(pgrId, currentDate);
        List<RotaJson> jsonList = new ArrayList<>();//转换成Json的List
        List<String> dateList = new ArrayList<>();//存放日期的List

        for (int i = 0; i < dbRotaList.size(); i++) {

            String dbDateStr = sdf.format(dbRotaList.get(i).getBookDay());
            RotaJson rotaJson = new RotaJson();

            if (jsonList.size() == 0) {
                rotaJson.setDate(dbDateStr);
                jsonList.add(rotaJson);
                dateList.add(dbDateStr);
            } else {
                if (!dateList.contains(dbDateStr)) {

                    rotaJson.setDate(dbDateStr);
                    jsonList.add(rotaJson);
                    dateList.add(dbDateStr);
                }

            }
        }

        for (int i = 0; i < dbRotaList.size(); i++) {
            String dbDateStr = sdf.format(dbRotaList.get(i).getBookDay());
            int dbBookTime = dbRotaList.get(i).getBookTime();
            for (int j = 0; j < jsonList.size(); j++) {
                if (dbDateStr.equals(jsonList.get(j).getDate())) {
                    RotaJson rotaJson = jsonList.get(j);
                    if (dbBookTime == 1) {
                        rotaJson.setSession1("可预约");
                    }
                    if (dbBookTime == 2) {
                        rotaJson.setSession2("可预约");
                    }
                    if (dbBookTime == 3) {
                        rotaJson.setSession3("可预约");
                    }
                    if (dbBookTime == 4) {
                        rotaJson.setSession4("可预约");
                    }
                    jsonList.set(j, rotaJson);
                }
            }
        }


//        for (int i = 0; i < jsonList.size(); i++) {
//            System.out.println(jsonList.get(i));
//        }
        String jsonStr = jsonUtil.toJSon(jsonList);

        return jsonStr;
    }

    /**
     * 将数据库中预约时间转换成1~28数字给前端（eg：1对应今天后第一天第一场，5对应今天后第二天第一场）
     *
     * @return1~28
     */
    @RequestMapping("/getRotaArray")
    @ResponseBody
    public List<Integer> getPgrRotaArray(@RequestBody String json) throws IOException {

        String pgrId = "";
        Map<String, String> map = jsonUtil.readValue(json, Map.class);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("id")) {
                pgrId = entry.getValue();
            }
        }

        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = sdf.format(currentDate);
        List<Rota> rotaList = pgrRotaService.getRota(pgrId, str);
        List<Integer> list = new ArrayList();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(currentDate);
        // 将时分秒,毫秒域清零
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        long currentTime = cal1.getTimeInMillis();

        for (int i = 0; i < rotaList.size(); i++) {

            Date dbDate = rotaList.get(i).getBookDay();
            int bookTime = rotaList.get(i).getBookTime();

            //跨年不会出现问题
            //如果时间为：2016-03-18 11:59:59 和 2016-03-19 00:00:01的话差值为 0
            long days = (dbDate.getTime() - currentTime) / (1000 * 3600 * 24);//算出今天后的第几天

            int number = 0;
            if (days > 0) {
                if (days > 1) {
                    number = bookTime + (int) (days - 1) * 4;
                } else {
                    number = bookTime;
                }
                list.add(number);
            }
        }

        return list;
    }

    /**
     * 跳转摄影师管理页面
     *
     * @return pgrInfoManage.html
     */
    @RequestMapping("/pgrInfoManage")
    public String pgrInfoManage() {

        return "pgrInfoManage";
    }

    /**
     * 查询登陆者对应admin表中的id
     *
     * @return 1超级管理员，2yige，3fuyou，4qinyu，5xiaoying
     */
    @RequestMapping("/getAuthority")
    @ResponseBody
    public String getAuthority(HttpSession session) {

        Admin admin = (Admin) webUtil.getCurrentUser(session);
        String id = admin.getId();

        Map<String, String> map = new HashMap<>();
        map.put("authority", String.valueOf(id));
        String json = jsonUtil.toJSon(map);

        return json;
    }

    /**
     * 删除摄影师信息
     *
     * @return "0"成功，"1"失败
     */
    @RequestMapping("/deleteInfo")
    @ResponseBody
    public String deleteInfo(@RequestBody String json) throws IOException {

        String pgrId = "";
        Map<String, String> map = jsonUtil.readValue(json, Map.class);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("id")) {
                pgrId = entry.getValue();
            }
        }
        String result = pgrInfoService.deleteInfoById(pgrId);
        Map<String, String> map1 = new HashMap<>();
        map.put("result", result);
        String json1 = jsonUtil.toJSon(map);
        return json1;
    }

    @RequestMapping("/pgrInfoAdd")
    public String pgrInfoAdd() {

        return "pgrInfoAdd";
    }


    /**
     * 修改摄影师信息
     */
    @RequestMapping(value = "/addInfo", method = RequestMethod.POST)
    @ResponseBody
    public String addInfo(@RequestBody String json) throws IOException {


        String id = UUID.randomUUID().toString().replace("-", "");
        String username = "";
        String password = "";
        String name = "";
        int age = 0;
        String mobile = "";
        String company = "";
        String gender = "";
        Map<String, String> map = jsonUtil.readValue(json, Map.class);

        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("id")) {
                id = entry.getValue();
            }
            if (entry.getKey().equals("username")) {
                username = entry.getValue();
            }
            if (entry.getKey().equals("password")) {
                password = entry.getValue();
            }
            if (entry.getKey().equals("name")) {
                name = entry.getValue();
            }
            if (entry.getKey().equals("age")) {
                age = Integer.valueOf(entry.getValue());
            }
            if (entry.getKey().equals("mobile")) {
                mobile = entry.getValue();
            }
            if (entry.getKey().equals("company")) {
                company = entry.getValue();
            }
            if (entry.getKey().equals("gender")) {
                gender = entry.getValue();
                if (gender.equals("1")) {
                    gender = "男";
                }
                if (gender.equals("2")) {
                    gender = "女";
                }
            }
        }
        Photographer photographer = new Photographer(id, name, mobile, username, password, company, age, gender);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH;mm:ss");
//        String dateString = sdf.format(new Date());
        photographer.setCreateTime(new Date());
        photographer.setStatus(Short.valueOf("0"));
        String ruselt = pgrInfoService.insertInfo(photographer);
        Map<String, String> map1 = new HashMap<>();
        map1.put("result", ruselt);
        String json1 = jsonUtil.toJSon(map1);

        return json1;
    }

    class RotaJson {
        String date;
        String session1;
        String session2;
        String session3;
        String session4;

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public String getSession1() {
            return session1;
        }

        public void setSession1(String session1) {
            this.session1 = session1;
        }

        public String getSession2() {
            return session2;
        }

        public void setSession2(String session2) {
            this.session2 = session2;
        }

        public String getSession3() {
            return session3;
        }

        public void setSession3(String session3) {
            this.session3 = session3;
        }

        public String getSession4() {
            return session4;
        }

        public void setSession4(String session4) {
            this.session4 = session4;
        }

        @Override
        public String toString() {
            return "RotaJson{" +
                    "date='" + date + '\'' +
                    ", session1='" + session1 + '\'' +
                    ", session2='" + session2 + '\'' +
                    ", session3='" + session3 + '\'' +
                    ", session4='" + session4 + '\'' +
                    '}';
        }

    }


    /**
     * 前台摄影师登陆接口
     */

    @ApiOperation("摄影师登陆")
    @ResponseBody
    @PostMapping("/login")
    public JSONResult PhrLogin(@RequestParam String username,
                               @RequestParam String password){
        return pgrInfoService.checkPhr(username,password);
    }

}
